package other.system.client.pms;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rkhd.platform.sdk.ScheduleJob;
import com.rkhd.platform.sdk.data.model.Product;
import com.rkhd.platform.sdk.data.model.SyncConfig__c;
import com.rkhd.platform.sdk.exception.ApiEntityServiceException;
import com.rkhd.platform.sdk.exception.ScriptBusinessException;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import com.rkhd.platform.sdk.param.ScheduleJobParam;
import com.rkhd.platform.sdk.service.FutureTaskService;
import com.rkhd.platform.sdk.service.XoqlService;
import com.rkhd.platform.sdk.task.FutureTask;
import org.apache.commons.lang.StringUtils;
import other.system.client.apitool.PMSClientUtils;
import other.system.client.util.HCDateUtils;
import other.system.client.util.HCXObjectService;
import other.system.client.util.ResultBody;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 同步 PMS 产品字段信息(产品分类二级领域和BU)
 * @Author: 黎炎松
 * @Date: 2024/7/11 18:26
 */
public class SyncProductFieldInfo implements ScheduleJob, FutureTask {

    private static HCXObjectService hcxObjectService = new HCXObjectService();

    private static XoqlService xoqlService = XoqlService.instance();

    private static final Logger logger = LoggerFactory.getLogger();

    private static final String LOGGER_MSG = "同步PMS产品分类二级领域和BU信息 ==> ";


    /**
     * 计划作业
     * @param scheduleJobParam
     */
    @Override
    public void execute(ScheduleJobParam scheduleJobParam) {
        try {
            logger.info(LOGGER_MSG + "触发计划作业");
            String messageId = FutureTaskService.instance().addFutureTask(getClass(), "");
            logger.info(LOGGER_MSG + "异步ID:" + messageId);
        } catch (Exception e) {
            logger.error(LOGGER_MSG + " ----- 发生异常：" + e.getMessage());
        }
    }

    /**
     * 异步任务
     * @param s
     * @throws ScriptBusinessException
     */
    @Override
    public void execute(String s) throws ScriptBusinessException {
        logger.info(LOGGER_MSG + "执行异步任务");
        syncProductFieldInfo();
    }

    public static void main(String[] args) throws ApiEntityServiceException {
        //new SyncProductFieldInfo().syncProductFieldInfo();
    }


    /**
     * 同步PMS产品分类二级领域和BU信息
     */
    public void syncProductFieldInfo() {
        try {
            logger.info(LOGGER_MSG + "处理开始");

            // 从数据配置表中获取上次更新时间
            String sql = "select id,lastSyncTime__c from syncConfig__c where syncKey__c = 'PMS_PRODUCT_INFO'";
            SyncConfig__c syncConfig = hcxObjectService.queryOne(sql, SyncConfig__c.class);
            if (syncConfig == null) {
                logger.debug(LOGGER_MSG + "配置信息不存在");
                return;
            }

            // 获取同步时间
            String startDate = syncConfig.getLastSyncTime__c();
            String endDate = HCDateUtils.dateToString(new Date(), HCDateUtils.FORMATTIME); // 同步结束时间
            if (StringUtils.isBlank(startDate)) {
                // 如果为空则退回1天前
                startDate = HCDateUtils.getDaysBeforeString(1, HCDateUtils.FORMATTIME);
            }

            // 查询参数
            JSONObject params = new JSONObject();
            params.put("startTime", startDate); // 更新开始时间
            params.put("endTime", endDate); // 更新结束时间
            //params.put("state", "1"); // 状态 1:有效 0：无效
            params.put("current", 1);
            params.put("pageSize", 5000);
            logger.debug(LOGGER_MSG + "params: " + params);

            ResultBody resultBody = PMSClientUtils.sendPost(params, PMSClientUtils.GET_PRODUCT_INFO_URL, "");
            if (!Objects.equals(resultBody.getCode(), "200")) {
                logger.debug(LOGGER_MSG + "获取PMS产品数据异常:" + resultBody.getMessage());
                return;
            }

            JSONObject result = (JSONObject) resultBody.getResult();
            List<JSONObject> productInfoList = JSONArray.parseArray(result.getString("records"), JSONObject.class);
            logger.info(LOGGER_MSG + "productInfoList: " + productInfoList.size());
            if (productInfoList.size() <= 0) {
                logger.debug(LOGGER_MSG + "暂无需要处理的产品二级领域数据");
                syncConfig.setLastSyncTime__c(endDate);
                syncConfig.setLastSyncCount__c(0L);
                hcxObjectService.update(syncConfig);
                return;
            }

            // 根据二级编码获取到对应的产品数据
            String productCategoryCodes = productInfoList.stream().map(v -> "'" + v.getString("productCategoryCode") + "'").collect(Collectors.joining(","));
            sql = "select id,productClassificationCode2__c from product where productClassificationCode2__c in (" + productCategoryCodes + ")";
            List<JSONObject> crmProductList = hcxObjectService.xoqlGetAllData(sql);

            // 获取新增、修改的数据
            List<Product> upProductList = new ArrayList<>();
            for (JSONObject productObj : productInfoList) {

                // 根据二级分类 获取分类下的产品
                String productCategoryCode = productObj.getString("productCategoryCode"); // 二级分类编码
                String productBu = productObj.getString("productBu"); // BU
                String secondaryDomain = productObj.getString("secondaryDomain"); // 二级领域
                Integer state = productObj.getInteger("state"); // 状态 1=有效，0=无效

                List<JSONObject> filterProductList = crmProductList.stream().filter(v -> Objects.equals(v.getString("productClassificationCode2__c"), productCategoryCode)).collect(Collectors.toList());

                // 赋值
                for (JSONObject product : filterProductList) {
                    Product upProduct = new Product();
                    upProduct.setId(product.getLong("id"));
                    upProduct.setProductBU__c(productBu); // 产品BU
                    upProduct.setProductFL2Status__c(state == 1 ? 1 : 2); // 产品分类(二级)状态
                    upProduct.setProductAreaL2__c(secondaryDomain); // 产品二级领域

                    // 编辑
                    upProductList.add(upProduct);
                }

                // 修改
                if (upProductList.size() > 100) {
                    Boolean update = hcxObjectService.batchUpdate(upProductList);
                    logger.debug(LOGGER_MSG + "update = " + update);
                    upProductList.clear();
                }

            }

            // 批量修改
            if (upProductList.size() > 0) {
                logger.debug(LOGGER_MSG + "修改的数据: " + upProductList.size());
                Boolean update = hcxObjectService.batchUpdate(upProductList);
                if (!update) {
                    logger.debug(LOGGER_MSG + "批量修改异常");
                    return;
                }
            }

            // 更新同步配置
            syncConfig.setLastSyncTime__c(endDate);
            syncConfig.setLastSyncCount__c(Long.valueOf(crmProductList.size()));
            Boolean update = hcxObjectService.update(syncConfig);
            if (!update) {
                logger.debug(LOGGER_MSG + "更新同步配置异常");
                return;
            }

            logger.debug(LOGGER_MSG + "处理成功");
        } catch (Exception e) {
            logger.info(LOGGER_MSG + "同步异常: " + e.getMessage());
        }
    }

}
